﻿using Autofac;
using Autofac.Extras.DynamicProxy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Suk.Common;
using Suk.Interface;
using Suk.Models.Config;
using Autofac.Core;
using log4net;

namespace Suk.Web
{
    public class DefaultModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {

            ServicesModel model = ConfigurationManager.GetAppSettings<ServicesModel>();
            foreach (ServiceModelService d in model.Services)
            {
                System.Reflection.Assembly assembly = System.Reflection.Assembly.Load(new System.Reflection.AssemblyName(d.ServiceNameSpace));
                System.Reflection.Assembly assemblyInterface = System.Reflection.Assembly.Load(new System.Reflection.AssemblyName(d.IServiceNameSpace));

                //注册服务
                builder.RegisterAssemblyTypes(assemblyInterface, assembly)
                        .AsImplementedInterfaces()//这里的AsImplementedInterfaces表示以接口的形式注册
                        .PropertiesAutowired()// 属性的自动注入
                        .InstancePerDependency()//生命周期 对每一个依赖或每一次调用创建一个新的唯一的实例。这也是默认的创建实例的方式。
                        .EnableInterfaceInterceptors(); // 开启拦截
            }

            //注册拦截器
            builder.RegisterType<LogInterceptor>(); 

            //注册 控制器
            var controllersTypesInAssembly = typeof(Startup).Assembly.GetExportedTypes()
                .Where(type => typeof(ControllerBase).IsAssignableFrom(type)).ToArray();
            builder.RegisterTypes(controllersTypesInAssembly).PropertiesAutowired().EnableClassInterceptors();


        }

        protected override void AttachToComponentRegistration(IComponentRegistry registry, IComponentRegistration registration)
        {
            registration.Preparing += OnComponentPreparing;
        }

        private static void OnComponentPreparing(object sender, PreparingEventArgs e)
        {
            //注册log4net 日志
            e.Parameters = e.Parameters.Union(
              new[]
              {
                    new ResolvedParameter(
                        (p, i) => p.ParameterType == typeof(ILog),
                        (p, i) => LogManager.GetLogger(Startup.loggerRepository.Name,p.Member.ReflectedType.BaseType.FullName)
                    ),
              });  
        }

    }
}
